/////////////////////////////////////////////////
//STEP 2: create the javascript application files
/////////////////////////////////////////////////

//this information will be stored in "FindItemsAdvancedSample.js" file

//the constructior of the FindItemsAdvancedSample. setting up variables and functions
function FindItemsAdvancedSample(config)
{
	this.items;
	this.itemcount;

	this.queryKeywords= null;
	/**
     * config object includes appId, affiliate tracking information, etc
     * @type Object
     */
	this.config = config;
	this.errorCount = 0;
	
	//defining the maximum number of results to show
	this.NumOfResults = results;
	//defining the interval for search results (in USD, $)
	this.highvalue = high;
	this.lowvalue = low;
	
	// function for error handling
	// @param {ErrorType} error
	this.onSomeItemsReturnedFailed = function(error) {
		if(isRegSearch == 1){
			Searchmsg.dismissMessage(GlobalSearchMessage);
			//GlobalRefMessage = msg.createStaticMessage('Refreshing');
			var userDiv = document.getElementById("itemContent");
			if(this.errorCount == 0) {
				var search = "<input id='LowValue' type='text' size='8' maxlength='12' VALUE='Low V $US'><input id='HighValue' type='text' size='8' maxlength='12' VALUE='High V $US'>";
				search += "<div><input id='query' type='text' size='22' maxlength='30' VALUE='Query Keyword'>";
				search += "<button onclick='goSearch();'>Search</button>"+"<br></div>";
				userDiv.innerHTML = search;
			}
			var errorHTML = "<div>" + error[0].longMessage + "<br>please try again</div>";
	    	userDiv.innerHTML = errorHTML + userDiv.innerHTML;
			this.errorCount ++;
		}
	};
		
	 // callback function for processing returned items
	 // @param {int} index
	this.onSomeItemsReturned = function (data) {
		//document.getElementById('itemContent').innerHTML += "<br>success";
			
		//change the data to a list based structure
		this.items = this.convertData4ItemListUI(data);
		this.itemcount = data.totalItems;
			
		//document.getElementById('itemContent').innerHTML += "<br>total items:"+data.totalItems;
			
	    //waiting until items for price ranges is received.
		if (this.items == null){
				return;
		}
		
		//change the global variable, searchList, to be the list
		if(isRegSearch == 1){
			searchList = this.items;
			//display the results from the list, to the user interface
			this.displayItems();
		}
		else{
			//check if the result is new; if so, update the Reminder object and the server
			this.checkIfNewReminder();
			Remindercnt++;
			//call the checking function for the next reminder:
			CheckForReminders();
			return;
		}
		
	}

////////////////////////////////////////////////
//STEP 3: set up the shopping web services calls
////////////////////////////////////////////////

	/**
	 * getting FindItemsAdvanced (Fia) requests
	 * @param {int} pmax, the upper limit of the price
	 * @param {int} pmin, the lower limit of the price
	 * @return {FindItemsAdvancedRequestType}
	*/
	this.getFiaRequest = function (pmax, pmin){
		var fiaRequest = new com.ebay.shoppingservice.FindItemsAdvancedRequestType({
			priceMax: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.USD, Value: pmax},
			priceMin: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.USD, Value: pmin},
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.BestMatch,
			QueryKeywords: this.queryKeywords,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.FixedPricedItem,
			maxEntries: this.NumOfResult
			});
		return fiaRequest;
	};

	/**
	 * call findItemsAdvanced shopping api
	 * @param {String} queryKeywords
	 */
	this.findItems = function(queryKeywords) {
		
		searchText = queryKeywords;
		if(isRegSearch == 1){
			//msg.dismissMessage(GlobalRefMessage);
			GlobalSearchMessage = Searchmsg.createStaticMessage('Searching for '+queryKeywords+"...");
			
		}
		
		this.queryKeywords = queryKeywords;
		
		//an instance of the shopping class
		var service = new com.ebay.shoppingservice.Shopping(this.config);

		//get FindItemsAdvanced request (with minimum and maximum values: 50,500 USD)
		var request1 = this.getFiaRequest(this.lowvalue,this.highvalue);
		//construct a ShoppingCallback object. callback in case of success and failure.
		var callback1 = new com.ebay.shoppingservice.ShoppingCallback({object: this, success:this.onSomeItemsReturned,
						failure:this.onSomeItemsReturnedFailed});
		//call the Fia function, with recently defined objects...
		var url = service.findItemsAdvanced(request1,callback1);
		
	};

///////////////////////////////////////////
//STEP 4: Add the returned data to an array
///////////////////////////////////////////

	/**
	 * convert returned items into format suitable for display in UI
	 * @param {FindItemsAdvancedResponseType} data
	 * @return {Array}, converted items
	 */
	this.convertData4ItemListUI = function(data) {
		
		if (data.searchResult !== null){
			var itemArray = data.searchResult[0].itemArray;
		}
		var items = [];
		if (itemArray) {
			var count = itemArray.item.length ;

			var i = 0;
			while (items.length<this.NumOfResults && i<count) {
				if (!itemArray.item[i].buyItNowAvailable
					&& itemArray.item[i].listingType.value == com.ebay.shoppingservice.ListingTypeCodeType.Chinese.value) {
					continue;
				}
				var item = itemArray.item[i];
				items.push(item);

				i++;
			}
		}
		
		return items;
	};

/////////////////////////////////////////
//STEP 5: Add code to display the results
/////////////////////////////////////////

	this.displayItems = function() {

		var priceRange = "$"+this.lowvalue+"-$"+this.highvalue;
		var userDiv = document.getElementById("itemContent");
		var newLine = "\n";
		
		var src = "<div id='products' style='/*float: left;*/ padding: 10px 0;font-family: Arial, sans-serif; font-size: small; border: 2px solid #D9E0E6; background: #FFE600'>" + newLine;
		//var src = "<div id='products'>"+newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td colspan='2' style='font-size: 120%; padding: 4px; font-weight:bold;'>Search Results for \"" + this.queryKeywords + "\"</td></tr>" + newLine;
		
		src = src + "<tr><td colspan='2' style='font-size: 110%; padding: 4px;'>" + priceRange + " (" + this.itemcount + " items found):</td></tr>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;
		
		//insert results information, using the function: ItemListUi.display()
		var empty = [];
		src = src + (new ItemListUI(this.items,1,empty).display());		
		
		src = src + "</td></tr>" + newLine;		
			
		//drop-down boxes
		/*
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr>";
		src = src + "<td align='left' valign='bottom'>";
		src = src + "<FORM name='buysellform'> <SELECT name='buysellList'> ";
		src+="<OPTION SELECTED value='0'>Item 1"+newLine; 
		for(var i=1; i<this.items.length; i++){
			var c= i+1;
			src+="<OPTION value='"+i+"'>Item "+c+newLine;
		}
		src+="</SELECT>"+newLine;  
		src+="<INPUT type='button' name='buybutton' value='buy' onClick='addWatch(";
		src+="document.buysellform.buysellList.options[document.buysellform.buysellList.selectedIndex].value";
		src+=", 1)'>";
		src+="<INPUT type='button' name='sellbutton' value='sell' onClick='addWatch(";
		src+="document.buysellform.buysellList.options[document.buysellform.buysellList.selectedIndex].value";
		src+=", 0)'></FORM>";
		
		src = src + "</td></tr>" + newLine;
		src = src + "</table>" + newLine;	
		*/ 
		//insert the search bar, for primary searches
		//if delete these lines, then (I think) delete only this block of lines.
		src = src + "<tr><td colspan='2'>" + newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr>";
		src = src + "<td align='left' valign='bottom'><button id='makeReminder' onclick='ReminderFunc()'>Remind Me</button></td>";
		src = src + "</tr><tr>";
		src = src + "<td style='padding: 0 4px 0 0;' bgcolor='#FFE600' align='right' valign='bottom'>" + newLine;
		src = src + "<input id='LowValue' type='text' size='5' maxlength='12' VALUE='"+this.lowvalue+"'><input id='HighValue' type='text' size='5' maxlength='12' VALUE='"+this.highvalue+"'>";
		src = src +	"<input id='query' type='text' size='20' maxlength='30' VALUE='"+this.queryKeywords+"'><button id='SearchButton' onclick='goSearch()'>Search</button>" + newLine;
		src = src + "</td></tr>" + newLine;
		src = src + "</table>" + newLine;
		
		src = src + "</td>" + newLine;
		src = src + "</tr>" + newLine;
		
		src = src + "</table>" + newLine;
		src = src + "</div>" + newLine;
		
		Searchmsg.dismissMessage(GlobalSearchMessage);
		//GlobalRefMessage = msg.createStaticMessage('Refreshing');	
		
		userDiv.innerHTML = src;
	};
	
	this.checkIfNewReminder = function(){
		if(!this.items)
			return;
		var singleItemID = this.items[0].itemID;
		var bool = 0;
		for (var i=0; i<Reminder.results[Remindercnt].length; i++){
			if(singleItemID == Reminder.results[Remindercnt][i])
				bool = 1;
		}
		if(bool == 1)
			return;
			
		Reminder.ID[Remindercnt] = singleItemID;
		isNewReminder = 1;			
		
	}
	
}//closing the entire class


// the function that searches Ebay and presents the results (in "itemContent" division)
function goSearch() {
	if(isRegSearch == 0){
		Searchmsg.createDismissibleMessage('Please wait a few seconds until EBay server is free for search');
		return;
	}
	isRegSearch = 1;
	var queryKeyword = null;
	var query = document.getElementById('query');
	
	if (query){
		queryKeyword = query.value;
		high = document.getElementById('HighValue').value;
		if(high == 'High V $US')
			high = 1000000;
		low = document.getElementById('LowValue').value;
		if(low == 'Low V $US')
			low = 0;
	}
		
	if (queryKeyword === null){
		//if no text was entered, only show search box
		var userDiv = document.getElementById("itemContent");
		var src = "<br><br><br><input id='LowValue' type='text' size='8' maxlength='12' VALUE='Low V $US'><input id='HighValue' type='text' size='8' maxlength='12' VALUE='High V $US'>";
		src += "<input id='query' type='text' size='20' maxlength='30' VALUE='Query Keyword'><button id='SearchButton' onclick='goSearch()'>Search</button>";
		userDiv.innerHTML = src;
		//for the first time, receive reminders:
		GetReminders();
		
		return;

	}

	var props = {};
	props["appId"] = appId;
	//Place your affiliate information
	//props["trackingId"] = ;
	//props["trackingPartnerCode"] = ;
	//props["affiliateUserId"] = ;
	//Place site id, default is 0 if you don't set
	props["siteId"] = 0;

	var config = new com.ebay.shoppingservice.ShoppingConfig(props);
	new FindItemsAdvancedSample(config).findItems(queryKeyword);
}


//call to receive the list of item ID's from the server
function CallForServerItems(){
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    var postData = {
            'userName' : userName
    };
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'showproducts';
                 
    gadgets.io.makeRequest(url, ItemsServerResponse, params); 
}


//insert the ID array to the global array, ItemIDList
function ItemsServerResponse(obj){
	if(obj === null || obj == null || obj.text == ''){
		StartEngine();
		return;
	}
	if(obj.data.products){
		ItemIDList = obj.data.products;
		ItemBid = obj.data.prices;
		IsBuying = obj.data.isbuy;
		WasTimeAlert = obj.data.timealert;
	}
	if(obj.data.history)
		HistoryIDList = obj.data.history;
	
	//after receiving the items, we can call the auto refresh function in a timeout
	timeoutID = setTimeout("autoRefresh()", TimeDiffToRef);
	//timeoutReminder = setTimeout("CheckForReminders()",TimeToRecheckReminder);
		
	StartEngine();

}


//for refreshing the items page
var CurrentItemIndex = 0;
var IDSize;
//The function converts the array of item ID's, to an array of item objects
//one by one
function IDToItem(){
	var currID;
	if(CurrentItemIndex == 0){
		if(RegOrHist == 1){
			IDSize = ItemIDList.length;
			itemsList = [];
		}
		else if(RegOrHist == 0){
			IDSize = HistoryIDList.length;
			historyList = [];
		}
		else{
			IDSize = Reminder.search.length;
			reminderList = [];	
		}
		
	}
	//this is a step after the last iteration
	if(RegOrHist != 2){
		if(CurrentItemIndex == IDSize){
			CurrentItemIndex = 0;
			refreshView();
			return;
		}
	}
	else if(CurrentItemIndex == IDSize){
		CurrentItemIndex = 0;
		showReminders();
		return;
	}
	
	if(RegOrHist == 1)
		currID = ItemIDList[CurrentItemIndex];
	else if (RegOrHist == 0)
		currID = HistoryIDList[CurrentItemIndex];
	else{//(RegOrHist == 2)
		if(Reminder.ID[CurrentItemIndex]  == "initialID"){
			CurrentItemIndex++;
			IDToItem();
			return;
		}
		else
			currID = Reminder.ID[CurrentItemIndex];
	}
	sendRqst(currID);
}


function sendRqst(currID){	
	var script_str = 'http://open.api.ebay.com/shopping?'+
	'callname=GetSingleItem'+
	'&appid='+appId+
	'&siteid=0'+
	'&version=517'+
	'&responseencoding=JSON'+
	'&callback=true'+
	'&ItemID='+currID;
	
	//prepare for the next iteration
	CurrentItemIndex++;

	var request = document.createElement('script');
	request.src=script_str;
	//call the GetSingleItem function of EBay (callback: _cb_GetSingleItem)
	document.body.appendChild(request);
	return;
}


//The callback function from the E-Bay results
function _cb_GetSingleItem(root)
{
	if(RegOrHist == 1){
		itemsList.push(root.Item);
	}
	else if(RegOrHist == 0){
		historyList.push(root.Item);	
	}
	else
		reminderList.push(root.Item);

	IDToItem();

}


//a variable to 
var indexToAdd;
//adds the given item to the watch list
function addWatch(index,buysell){

	var tabName = tabs.getSelectedTab().getName();
	var ID;
	indexToAdd = index;
	var picLink;
	var urlLink;
	var title;
	
	if(tabName != "Reminder"){	
		//preferred to use append so that we could delete it later? also,
		ID = searchList[index].itemID;
		for(var i=0; i<ItemIDList.length; i++){
			if(ItemIDList[i] == ID)
				return;
		}
		picLink = searchList[index].galleryURL;
		urlLink = searchList[index].viewItemURLForNaturalSearch;
		title = searchList[index].title;
	}
	else{
		ID = Reminder.ID[index];
		picLink = reminderList[index].GalleryURL;
		urlLink = reminderList[index].ViewItemURLForNaturalSearch;
		Title = searchList[index].title;
		buysell = 1;
	}
	//isbuy is 1. if and when, we want to add the option for selling items, change the string/function to fit
	//add the item to the server (for next load of the gadget)
    var postData = {
        'userName' : userName, 'content1' : ID, 'isbuy' : buysell, 'ProductPic' : picLink, 'ProductName' : title, 'cellNum' : TelNum, 'ProductURL' : urlLink
    };
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'addproduct';
    
    IsBuying.push(buysell);    
    gadgets.io.makeRequest(url, ReminderEmptyResponse, params); 
    
	//var tabName = tabs.getSelectedTab().getName();
	//var ID;
	if(tabName != "Reminder"){
		//no need to change the item list right away (itemsList!=ItemIDList)...
		//do that only when changed the view tab (to history or auctions)
		ID = searchList[indexToAdd].itemID;
	}
	else
		ID = Reminder.ID[indexToAdd];
	
	//change the global ID array to be the current array                                                             
    ItemIDList.push(ID);
    //IsBuying.push('1');
    ItemBid.push(maxPrice);
    WasTimeAlert.push('0');
    //change the global ID array to be the current array
    var tmpflag = -1;                                                             
    for(var i=0; i<HistoryIDList.length; i++){
    	if(ID*1 == HistoryIDList[i]*1)
    		tmpflag = i;    	
    }
    if(tmpflag != -1){
    	HistoryIDList.splice(tmpflag, 1);
    }
    
    HistoryIDList.push(ID);
    
    if(HistoryIDList.length == HISTORYITEMS+1)
    	HistoryIDList.splice(0,1);
    //again, no need to change the item list right away...
	//do that only when changed the view tab (to history or auctions)
	
	if(tabName == "Reminder")
		deleteReminder(indexToAdd);
	
}


//show item contents on screen (according to history or regular view)
function refreshView(){	
	//change the timeleft string to look better...
	changeTimeStrings();
	var newLine = "\n";
	var src = '';
	src = src + "<tr><td colspan='2'>";
	if(RegOrHist == 1){
		msg.dismissMessage(GlobalRefMessage);
		if(itemsList.length == 0)
			src = src + "<br><br>You have no auctions in interest<br>";
		else{
			
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;
		src = src + (new ItemListUI(itemsList,2,IsBuying).display());
		src = src + "</td></tr></table>";
			
		}

	}
	else{
		if(historyList.length == 0)
			src = src + "<br><br>Your history is empty<br>";
		else
			src = src + (new ItemListUI(historyList,0,IsBuying).display());
		
	}
	//insert results information, using the function: ItemListUi.display()		
	src = src + "</td></tr>";

	if(RegOrHist == 1){
		var newLine = "\n";
		/*
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr>";
		src = src + "<td align='left' valign='bottom'>";
		src = src + "<FORM name='biddeleteform'> <SELECT name='biddeleteList'> ";
		src+="<OPTION SELECTED value='0'>Item 1"+newLine; 
		for(var i=1; i<itemsList.length; i++){
			var c= i+1;
			src+="<OPTION value='"+i+"'>Item "+c+newLine;
		}
		//var tmpstr = "document.biddeleteform.biddeleteList.options[document.biddeleteform.biddeleteList.selectedIndex].value";
		src+="</SELECT>"+newLine;  
		src+="<INPUT type='button' name='deletebutton' value='delete' onClick='deleteAuction(";
		src+="document.biddeleteform.biddeleteList.options[document.biddeleteform.biddeleteList.selectedIndex].value"+", deleteAuctionResp)'>";
		src+="<INPUT type='button' name='highpricebutton' value='my bid' onClick='changeToHighBid(";
		src+="document.biddeleteform.biddeleteList.options[document.biddeleteform.biddeleteList.selectedIndex].value"+")'></FORM>";
		src+="</td></tr></table>";
		*/
		
		document.getElementById("ItemsList").innerHTML = src;
		
		//call another refresh in TimeDiffToReff milliseconds...
		timeoutID = setTimeout("autoRefresh()", TimeDiffToRef);
		
		var tmpIndex = "-1";
		for(i=0; i<itemsList.length; i++){
			if(IsBuying[i]=='1' && itemsList[i].ConvertedCurrentPrice.Value.toFixed(2)*1 > ItemBid[i]*1){
				tmpIndex='"'+i+'"';
			}
		}
			
		var timeString = computeTimeLeft();
		
		updateTimeAndPrice(timeString,tmpIndex);
	}
	else{
		document.getElementById("HistoryList").innerHTML = src;
		if(RefreshWaitReg == 1)
			refreshButtonAuction();
	}
}


function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}


//function to receive the auto refresh, and refresh only if needed
function autoRefresh(){

	msg.dismissMessage(GlobalRefMessage);
	GlobalRefMessage = msg.createStaticMessage('Refreshing');

	RegOrHist = 1;
	if(CurrentItemIndex != 0){
		RefreshWaitReg = 1;
		return;
	}
	//CurrentItemIndex = 0;
	RefreshWaitReg = 0;
	//document.getElementById("ItemsList").innerHTML = "<br><br>...Refreshing...<br><br>";

	IDToItem();
}


//after clicking the refresh button in the auctions tab
function refreshButtonAuction(){
	
	msg.dismissMessage(GlobalRefMessage);
	GlobalRefMessage = msg.createStaticMessage('Refreshing...');
	
	if(CurrentItemIndex != 0){
		RefreshWaitReg = 1;
		return;
	}
	
	//clear the auto timeout, and create another auto timeout after finishing the refresh
	clearTimeout(timeoutID);
	RefreshWaitReg = 0;
	RegOrHist = 1;
	//CurrentItemIndex = 0;

	//document.getElementById("ItemsList").innerHTML = "<br><br>...Refreshing...<br><br>";
	
	IDToItem();
}


function refreshHistory(){
	
	if(CurrentItemIndex != 0){
		//need to call the function back after finishing receiving the auctions information
		RefreshWaitHist = 1;
		return;
	}
	
	RefreshWaitHist = 0;
	RegOrHist = 0;
	CurrentItemIndex = 0;
		
	IDToItem();
}


var indexToDelete;
//need to make calling function...
function deleteAuction(index, response){
	
	indexToDelete = index;

	var ID = itemsList[indexToDelete].ItemID;
	
	//add the item to the server (for next load of the gadget)
    var postData = {
        'userName' : userName, 'content2' : ID
    };
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'delete';
                 
    gadgets.io.makeRequest(url, response, params); 
}


//receive new ID list, insert it and refresh the view
function deleteAuctionResp(obj){
	
	if(obj === null)
		return;                                                             
    ItemIDList.splice(indexToDelete,1);
    ItemBid.splice(indexToDelete,1);
    IsBuying.splice(indexToDelete,1);
    WasTimeAlert.splice(indexToDelete, 1);

	refreshButtonAuction();
}


function changeTimeStrings(){
	var max;
	var str = '';
	var tmpstr;
	var tmpchar;
	if(RegOrHist == 1)
		max = itemsList.length;
	else
		max = historyList.length;
	for(var i=0; i<max; i++){
		//for a single item, change its time string
		if(RegOrHist==1)
			tmpstr=itemsList[i].TimeLeft;
		else{
			tmpstr=historyList[i].TimeLeft;		
		}
		//first and last characters are 'S' and 'P'
		for(var j=tmpstr.length-1; j>0; j--){
			tmpchar = tmpstr.charAt(j);
			if(tmpchar!='M' && tmpchar!='H' && tmpchar!='D' && tmpchar!='T')
				str= tmpchar+str;
			else if(tmpchar!='T')
				str= tmpchar+' '+str;
		}
		if(RegOrHist==1)
			itemsList[i].TimeLeft=str;
		else
			historyList[i].TimeLeft=str;
		str = '';	
	}
}


function computeTimeLeft(){
	var arr = [];
	var multiplier = [1, 60, 3600, 86400];
	var tmpstr;
	var cnt = 0;
	var tmpVal;
	for(var i=0; i<itemsList.length; i++){
		tmpstr = itemsList[i].TimeLeft;
		tmpVal = 0;
		//alert("tmpstr.split: "+tmpstr.split(" "));
		var tmparr = tmpstr.split(' ');
		//alert(tmparr.length);
		for(var j=tmparr.length-1; j>-1; j--){
			if(tmparr[j][tmparr[j].length-1] == 'S')
				cnt = 0;
			else if(tmparr[j].charAt(tmparr[j].length-1) == 'M')
				cnt = 1;
			else if(tmparr[j].charAt(tmparr[j].length-1) == 'H')
				cnt = 2;
			else if(tmparr[j].charAt(tmparr[j].length-1) == 'D')
				cnt = 3;
			tmparr[j] = tmparr[j].substr(0, tmparr[j].length-1);
			tmpVal+=parseInt(tmparr[j])*parseInt(multiplier[cnt]);
		}
		arr.push(tmpVal);
	}
	return arr;
}


//change the Bid of the product to the price shown
function changeToHighBid(index){
	
	if(IsBuying[index]=='0')
		return;
	
	ItemBid[index]= itemsList[index].ConvertedCurrentPrice.Value.toFixed(2);
	//update the server
	//, 'URL' : itemsList[index].ViewItemURLForNaturalSearch
	var postData = {
        'userName' : userName, 'ID' : ItemIDList[index], 'price' : ItemBid[index]
    };
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    
    var url = ServerHome + 'update';
           
    gadgets.io.makeRequest(url, updateToHighResponse, params);
}


function updateToHighResponse(obj){
	if(obj === null)
		return;
}


//this function will update the server with a price of product and with the ID that was outbid
function updateTimeAndPrice(timeString, index){
	var postData;
	
	var timeID = "-1";
	for(var i=0; i<timeString.length; i++){
		if(timeString[i]*1 < TIMETOALERT && WasTimeAlert[i] == '0'){
			//items to sell are not notified. it's expressed in WasTimeAlert initial value for sell items: '1'
			timeID = ItemIDList[i];
			WasTimeAlert[i] = '1';
		}
	}

	if(index != "-1" && timeID != "-1"){
		ItemBid[index] = maxPrice;
		var timeInMin = TIMETOALERT/60;
    	postData = {
        	'userName' : userName, 'timeID' : timeID,  'ID' : ItemIDList[index], 'price' : ItemBid[index], 'timeToAlert' : timeInMin
    	};
    	msg.createDismissibleMessage("you were outbid... item number"+index+" on the list",10);
    	msg.createDismissibleMessage("An auction,  is about to end!");
	}
    else if(index != "-1"){
    	ItemBid[index] = maxPrice;
    	postData = {
        	'userName' : userName, 'ID' : ItemIDList[index], 'price' : ItemBid[index]
    	};
    	msg.createDismissibleMessage("you were outbid... item number"+index+" on the list", 10);
    }
    else if (timeID != "-1"){
		var timeInMin = TIMETOALERT/60;
    	postData = {
        	'userName' : userName, 'timeID' : timeID, 'timeToAlert' : timeInMin
    	};
    	msg.createDismissibleMessage("An auction is about to end!");
    }
    else
    	return;
    	
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    
    var url = ServerHome + 'update';           
    gadgets.io.makeRequest(url, updateToHighResponse, params);
	
}


//clearing the history of the user...
function clearHistory(){
	var postData = {
        'userName' : userName
    };
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    
    var url = ServerHome + 'clear';           
    gadgets.io.makeRequest(url, clearHistoryResp, params);
}


//a response function to clear the history
function clearHistoryResp(obj){
	if(obj === null)
		return;
	
	HistoryIDList = [];
	refreshHistory();
}


/***********************************/
/////////////Reminders//////////////
/**********************************/

//this function will save the queryKeyword so that every time the gadget opens,
//new results for the keyword'll be searched. if there are new results, alert on them
function ReminderFunc(){

	var tmpstr = "";
	//create the special string for containing the reminders old results...
	for(var i=0; i<searchList.length; i++){
		tmpstr+= '"'+searchList[i].itemID+'"';
		if(i<searchList.length-1){
			tmpstr += ", ";
		}
	}
	
	var postData = {
	'SearchString' : searchText, 'top5results' : tmpstr, 'UserName' : userName, 'minPrice' : low, 'maxPrice' : high, 'ID' : 'initialID'
	};
	
	var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);  
    var url = ServerHome + 'addreminder'; 
	
    gadgets.io.makeRequest(url, addRemindResp, params);
	
	//alert('the string: '+searchText+' is in "reminding" mode');
}


function addRemindResp(obj){
	if(obj === null)
		return;
		
	GetRemindersStart();
}


var initReminders = 1;
function GetReminders(){
	if(initReminders == 1)
		GetRemindersStart();
}


//receives the reminder items from the server
function GetRemindersStart(){
    initReminders = 0;
	var postData = {
        	'UserName' : userName
    	};

    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'sendremindertoclient';
    gadgets.io.makeRequest(url, GetReminderResp, params);

}


//set the object Reminder to contain the reminders...
function GetReminderResp(obj){
	if(obj === null || obj == null || obj.text==""){
		document.getElementById("ReminderContent").innerHTML = "<br><br>You have No Reminders";
		return;
	}
	Reminder=obj.data;

	Remindercnt = 0;
	CheckForReminders();
}


//checks for items in the reminder
function CheckForReminders(){
	
	//clearTimeout(timeoutReminder);
	isRegSearch = 0;
	if(Reminder == null){
		isRegSearch = 1;
		return;
	}
	if(Remindercnt == 0){
		//need to return the values at the end to their default values
		//document.getElementById("ReminderContent").innerHTML = "<br><br><br>Refreshing...";
		Remmsg.dismissMessage(GlobalReminderMessage);
		GlobalReminderMessage = Remmsg.createStaticMessage('Refreshing');
		results = 1;
	}
	if(isNewReminder == 1){
		isNewReminder = 0;
		//update the server to the new reminder in place: Remindercnt-1
		updateReminderServer(-1);
		return;
	}
	
	if(Remindercnt < Reminder.search.length){
		if(Reminder.ID[Remindercnt] == "initialID"){
			queryKeyword = Reminder.search[Remindercnt];
			high = Reminder.high[Remindercnt];
			low = Reminder.low[Remindercnt];

			var props = {};
			props["appId"] = appId;
			//Place your affiliate information
			//props["trackingId"] = ;
			//props["trackingPartnerCode"] = ;
			//props["affiliateUserId"] = ;
			//Place site id, default is 0 if you don't set
			props["siteId"] = 0;
			var config = new com.ebay.shoppingservice.ShoppingConfig(props);
			new FindItemsAdvancedSample(config).findItems(queryKeyword);
			return;
		}
		else{
			Remindercnt++;
			CheckForReminders();
			return;
		}
			
	}	
	//return the values at the end to their default values
	isRegSearch = 1;
	Remindercnt = 0;
	//high = prefs.getInt("HighValue");
	//low = prefs.getInt("LowValue");
	results = prefs.getInt("ResultsShown");	
	if(Reminder.search.length !=0){
		RegOrHist = 2;
		CurrentItemIndex = 0;
		IDToItem();
	}
	
}


function changeReminderTimeStrings(index){
	var max;
	var str = '';
	var tmpstr;
	var tmpchar;
	
	//for a single item, change its time string
	tmpstr=reminderList[index].TimeLeft;
		
	//first and last characters are 'S' and 'P'
	for(var j=tmpstr.length-1; j>0; j--){
		tmpchar = tmpstr.charAt(j);
		if(tmpchar!='M' && tmpchar!='H' && tmpchar!='D' && tmpchar!='T')
			str= tmpchar+str;
		else if(tmpchar!='T')
			str= tmpchar+' '+str;
	}
	reminderList[index].TimeLeft=str;
	
}


//forms the view of the Reminder tab from the reminderList
function showReminders(){
	
	var tmp = [];
	var src = '';
	var cnt = 0;
	var remID = [];
	for(var i=0; i<Reminder.ID.length; i++){
		src +="<u>search string: <b>"+Reminder.search[i]+"</b></u><br>";
		if(Reminder.ID[i] != "initialID"){
			remID = [];
			remID.push(reminderList[cnt]);
			changeReminderTimeStrings(cnt);
			cnt++;
			src = src + "A new result was found<br>";
			src = src + "<tr><td colspan='2'>";
			src = src + (new ItemListUI(remID,0,tmp).display());
			src = src + "</td></tr>";
					
			//insert results information, using the function: ItemListUi.display()	
		}
		else{
			src = src + "No new results are found<br>";
		}
		src+= "<br>"
	}
	
	var newLine = "\n";
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr>";
		src = src + "<td align='left' valign='bottom'>";
		src = src + "<FORM name='deleteRemForm'> <SELECT name='deleteRemList'> ";
		src+="<OPTION SELECTED value='0'>Reminder 1"+newLine; 
		for(i=1; i<Reminder.search.length; i++){
			var c= i+1;
			src+="<OPTION value='"+i+"'>Reminder "+c+newLine;
		}
		//var tmpstr = "document.biddeleteform.biddeleteList.options[document.biddeleteform.biddeleteList.selectedIndex].value";
		src+="</SELECT>"+newLine;  
		src+="<INPUT type='button' name='deleteReminderbutton' value='delete' onClick='deleteReminder(";
		src+="document.deleteRemForm.deleteRemList.options[document.deleteRemForm.deleteRemList.selectedIndex].value"+")'>";
		src+="<INPUT type='button' name='updateReminderbutton' value='re-search' onClick='updateReminderServer(";
		src+="document.deleteRemForm.deleteRemList.options[document.deleteRemForm.deleteRemList.selectedIndex].value"+")'>";
		src+="<INPUT type='button' name='addReminderbutton' value='add' onClick='addWatch(";
		src+="document.deleteRemForm.deleteRemList.options[document.deleteRemForm.deleteRemList.selectedIndex].value"+")'></FORM>";
		src+="</td></tr></table>";
	
	Remmsg.dismissMessage(GlobalReminderMessage);
	//GlobalRefMessage = msg.createStaticMessage('Refreshing');
	
	document.getElementById("ReminderContent").innerHTML = src;
	//timeoutReminder = setTimeout("CheckForReminders()",TimeToRecheckReminder);
	
	
}


//delete the reminders
function ClearReminder(){
	
	var postData = {
        'UserName' : userName
    };
    
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'clearreminders';   
    gadgets.io.makeRequest(url, ClearReminderResp, params);
	
}	
	

function ClearReminderResp(obj){
	if(obj === null)
		return;
		
	Reminder = null;	
}


var Reminderindextodel;
function deleteReminder(index){
	Reminderindextodel = index;
	var postData = {
        'UserName' : userName, 'SearchString' : Reminder.search[index]
    };
    
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'deletereminder';   
    gadgets.io.makeRequest(url, deleteReminderResp, params);
}


function deleteReminderResp(obj){
	if(obj == null)
		return;
	GetRemindersStart();
}


//update the reminder to the server side (client side was already updated);
function updateReminderServer(index){

	var ID;
	var minRemPrice;
	var maxRemPrice;
	var search;
	var results = "";
	
 	if(index == -1){
		ID = Reminder.ID[Remindercnt-1];
		results = Reminder.results[Remindercnt-1];
		search = Reminder.search[Remindercnt-1];
		minRemPrice = Reminder.low[Remindercnt-1];
		maxRemPrice = Reminder.high[Remindercnt-1];
	}
	else{/*index != -1*/
		if(Reminder.ID[index]=='initialID'){//in case re-search was pressed on Reminder with no new result
			Remmsg.createDismissibleMessage("No new results were found for this reminder");
			return;
		}
		
		//recreating the 'refreshing...' message
		Remmsg.dismissMessage(GlobalReminderMessage);
		GlobalReminderMessage = Remmsg.createStaticMessage('Refreshing');	
		
		ID = 'initialID';
		search = Reminder.search[index];
		minRemPrice = Reminder.low[index];
		maxRemPrice = Reminder.high[index];
		
		Reminder.results[index][Reminder.results[index].length] = Reminder.ID[index];
		//create the special string for containing the reminders old results...
		for(var i=0; i<Reminder.results[index].length; i++){
			results+= '"'+Reminder.results[index][i]+'"';
			if(i<Reminder.results[index].length-1){
				results += ", ";
			}
		}
		
	}
		
	//deleting the reminder
    var postData = {
        	'UserName' : userName, /*'reminderID' : ID,*/ 'SearchString' : search
    	};
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);
    var url = ServerHome + 'deletereminder';
   
    gadgets.io.makeRequest(url, ReminderEmptyResponse, params);

	//adding the newely updated Reminder
	postData = {
		'SearchString' : search, 'top5results' : results, 'UserName' : userName, 'minPrice' : minRemPrice, 'maxPrice' : maxRemPrice, 'ID' : ID
	};
	params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(postData);  
    url = ServerHome + 'addreminder'; 

	if(index==-1){
    	gadgets.io.makeRequest(url, ReminderServerResp2, params);
	}
	else{
		gadgets.io.makeRequest(url, deleteReminderResp, params);
	}

}


function ReminderEmptyResponse(obj){
	
}


function ReminderServerResp2(obj){
	CheckForReminders();
}

